package util

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
)

func HttpGet(url string) string {
	response, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	log.Println("Get:", string(body))
	return string(body)
}

func HttpPost(url string, data string) string {
	log.Println("Url:", url)
	log.Println("Post:", string(data))
	return HttpPostData(url, []byte(data))
}

func HttpPostData(url string, data []byte) string {
	// application/json;charset=utf-8
	response, err := http.Post(url, "application/octet-stream", bytes.NewBuffer(data))
	if err != nil {
		log.Println(err)
		return ""
	}
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	//time.Sleep(1 * time.Second)
	return string(body)
}

func HttpPortScanner(ipStr string, port int) bool {
	server := fmt.Sprintf("%s:%d", ipStr, port)
	tcpAddr, err := net.ResolveTCPAddr("tcp4", server)
	if err != nil {
		return false
	}
	conn, err1 := net.DialTCP("tcp4", nil, tcpAddr)
	if err1 != nil {
		return false
	}
	defer conn.Close()
	return true
}
